import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from '@/app.module';
import { GlobalExceptionFilter } from '@/common/global-exception.filter';
import { LoggingService } from '@/services/logging.service';
import { AppConfigService } from '@/common/config.service';

async function bootstrap() {
    const app = await NestFactory.create(AppModule);

    // 获取配置服务
    const configService = app.get(AppConfigService);
    const loggingService = app.get(LoggingService);

    // 全局异常过滤器
    app.useGlobalFilters(new GlobalExceptionFilter(loggingService));

    // 全局验证管道
    app.useGlobalPipes(new ValidationPipe());

    // 全局前缀
    app.setGlobalPrefix('api');

    // 启动应用
    const port = configService.getPort();
    await app.listen(port);

    // 记录启动日志
    loggingService.app(`🚀 应用启动成功，监听端口: ${port}`);
    loggingService.app(configService.getEnvironmentSummary());

    // 优雅关闭
    process.on('SIGTERM', async () => {
        loggingService.app('收到 SIGTERM 信号，开始优雅关闭...');
        await app.close();
        loggingService.app('应用已关闭');
        process.exit(0);
    });

    process.on('SIGINT', async () => {
        loggingService.app('收到 SIGINT 信号，开始优雅关闭...');
        await app.close();
        loggingService.app('应用已关闭');
        process.exit(0);
    });
}

bootstrap().catch((error) => {
    console.error('启动失败:', error);
    process.exit(1);
});
